from fastapi import HTTPException
from src.db import db_models


async def score_add_serives(add_model):
    id_exist = await db_models.Stu_Info.filter(stu_id=add_model.s_id).first()
    if not id_exist:
        raise HTTPException(
            status_code=404,
            detail=f"这个学生id:{add_model.s_id}不存在"
        )

    await db_models.Score.create(stu_id_id=add_model.s_id,
                                 stu_grade=add_model.stu_grade,
                                 test_time=add_model.test_time,
                                 stu_class_name=id_exist.stu_class_name,
                                 stu_name=id_exist.stu_name,

                                 )
    return {"message": "添加成功"}


async def select_one_student(s_id):
    id_exist = await db_models.Score.filter(stu_id=s_id).values()
    if not id_exist:
        raise HTTPException(
            status_code=404,
            detail=f"学生id{s_id}不存在"
        )
    return id_exist


async def score_put_services(s_id, student_score):
    id_exist = await db_models.Score.filter(stu_id=s_id, test_time=student_score.test_time).values()
    if not id_exist:
        raise HTTPException(
            status_code=400,
            detail=f"学生id{s_id}不存在,或者考核序次{student_score.test_time}不存在，无法更改"
        )

    student_score_grade = student_score.stu_grade  # 拿到更改后的成绩
    await db_models.Score.filter(stu_id=s_id, test_time=student_score.test_time).update(stu_grade=student_score_grade)
    return {
        "message": "更新成功"
    }


async def delete_score_services(score_model):
    id_exist = await db_models.Score.filter(stu_id=score_model.s_id, test_time=score_model.test_time).values()
    if not id_exist:
        raise HTTPException(
            status_code=400,
            detail=f"学生id{score_model.s_id}不存在,或者{score_model.test_time}不存在，无法删除"
        )
    await db_models.Score.filter(stu_id=score_model.s_id, test_time=score_model.test_time).delete()
    return {"message": "删除成功"}
